<template>
  <BasicModal width="800px" v-bind="$attrs" @register="registerModal" :title="modalTitle" @ok="onButtonOkClick">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
import {defineComponent, ref, unref, inject, reactive, computed, watch} from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { certificateInfoFormSchema } from './certificateInfo.data';
import { useMessage } from '/@/hooks/web/useMessage';
import { OperationTypeEnum } from '/@/enums/appEnum';
import {getEpibolyPersonByUnitId, queryEpibolyUnit} from '/@/api/ehs/epiboly';


import {
  addCertificateInfo,
  getCertificateInfo,
  queryCertificateInfo,
  updateCertificateInfo
} from '/@/api/ehs/certificateInfo';
import { CertificateDto } from '/@/api/ehs/model/certificateInfoModel';
import { uploadApi } from '/@/api/platform/upload';
import { useGlobSetting } from '/@/hooks/setting';
import {getOrgUsers} from "/@/api/ehs/organization";

const { createMessage } = useMessage();

export default defineComponent({
  name: 'AddOrUpdateCertificateInfo',
  components: { BasicModal, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    // 基础状态
    const op = ref(OperationTypeEnum.UN_KNOWN);
    const dataId = ref('');
    const orgcode = ref('');
    const moduleName = inject<string>('moduleName') || '资质证照';
    const modalTitle = ref('资质证照');

    // 数据缓存
    const dataCache = reactive({
      epibolyUnits: [],     // 相关方单位
      epibolyPersons: [],   // 相关方人员
      systemPersonnel: [],   // 系统人员
      unitPersonsMap: new Map() // 单位ID -> 人员列表的映射 ✅ 新增
    });

    // 当前表单状态 - 响应式对象
    const formState = reactive({
      isepiboly: false,
      isperson: false,
      selectedEpibolyUnit: null // ✅ 当前选择的相关方单位
    });

    // 3. 新增：相关方单位选项计算属性
    const epibolyUnitOptions = computed(() => {
      return dataCache.epibolyUnits.map(item => ({
        label: item.unitname || item.name,
        value: item.unitid || item.id
      }));
    });

    // 计算属性：持证人选项
    const holdUserOptions = computed(() => {
      const { isepiboly, isperson, selectedEpibolyUnit } = formState;


      // 本单位单位证照 - 不显示持证人选择
      if (!isepiboly && !isperson) {
        return [];
      }

      // 相关方单位证照
      if (isepiboly && !isperson) {
        return dataCache.epibolyUnits.map(item => ({
          label: item.unitname || item.name,
          value: item.unitid || item.id
        }));
      }

      // ✅ 关键：相关方人员证照 - 需要先选择单位
      if (isepiboly && isperson) {
        if (!selectedEpibolyUnit) {
          return []; // 未选择单位时返回空数组
        }

        // 返回选中单位下的人员
        const unitPersons = dataCache.unitPersonsMap.get(selectedEpibolyUnit) || [];
        return unitPersons.map(person => ({
          label: person.username || person.name,
          value: person.userid || person.id
        }));
      }

      // 本单位人员证照
      if (!isepiboly && isperson) {
        return dataCache.systemPersonnel.map(item => ({
          label: item.username || item.name,
          value: item.userid || item.id
        }));
      }

      return [];
    });

    // 计算属性：占位符文本
    const placeholderText = computed(() => {
      const { isepiboly, isperson } = formState;

      if (!isepiboly && !isperson) return '';
      if (isepiboly && !isperson) return '请选择相关方单位';
      if (isepiboly && isperson) return '请选择相关方人员';
      if (!isepiboly && isperson) return '请选择系统人员';

      return '请选择持证人';
    });

    // 5.  新增：加载指定单位的人员
    async function loadUnitPersons(unitId) {
      try {

        // 如果已经加载过，直接返回缓存
        if (dataCache.unitPersonsMap.has(unitId)) {
          return dataCache.unitPersonsMap.get(unitId);
        }

        // 调用API加载该单位的人员
        const unitPersons = await getEpibolyPersonByUnitId(unitId);

        if (unitPersons && Array.isArray(unitPersons)) {
          const formattedPersons = unitPersons.map(person => ({
            userid: person.id,
            username: person.name
          }));

          // 缓存结果
          dataCache.unitPersonsMap.set(unitId, formattedPersons);

          return formattedPersons;
        } else {
          console.warn(`单位 ${unitId} 没有返回有效的人员数据`);
          dataCache.unitPersonsMap.set(unitId, []);
          return [];
        }
      } catch (error) {
        console.error(`加载单位 ${unitId} 人员失败:`, error);
        dataCache.unitPersonsMap.set(unitId, []); // 失败时也要缓存空数组
        createMessage.warning(`加载单位人员失败: ${error.message}`);
        return [];
      }
    }

    // 获取文件扩展名
    function getFileExtension(fileName) {
      if (!fileName) return '';
      const parts = fileName.split('.');
      return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
    }

    // 6. 修改 createDynamicFormSchema 中的字段处理
    function createDynamicFormSchema() {
      return certificateInfoFormSchema.map(schema => {

        // ✅ 处理相关方单位字段
        if (schema.field === 'epibolyunit') {
          return {
            ...schema,

            componentProps: {
              ...schema.componentProps,
              options: [], // 初始为空，后续动态更新
              onChange: async (value, option) => {

                // 更新选中的单位
                formState.selectedEpibolyUnit = value;

                // 清空人员选择
                setFieldsValue({
                  holdusername: undefined,
                  holduserid: undefined
                });

                if (value) {
                  // 加载该单位下的人员
                  await loadUnitPersons(value);

                  // 触发人员选项更新
                  setTimeout(() => {
                    updateHoldUserField();
                  }, 100);
                }
              }
            }
          };
        }

        // 修改持证人字段的显示逻辑
        if (schema.field === 'holdusername') {
          return {
            ...schema,
            label: '持证人/单位', // 默认标签，会被动态更新
            show: ({ values }) => {
              // 同步表单状态
              formState.isepiboly = values.isepiboly;
              formState.isperson = values.isperson;

              // ✅ 关键逻辑：相关方人员证照需要先选择单位
              if (values.isepiboly === true && values.isperson === true) {
                return !!values.epibolyunit; // 必须先选择单位
              }

              // 其他情况：相关方单位证照 或 本单位人员证照
              return values.isepiboly === true || values.isperson === true;
            },
            componentProps: {
              ...schema.componentProps,
              options: [],
              placeholder: '请选择持证人',
              fieldNames: { label: 'label', value: 'value' },
              allowClear: true,
              onChange: (value, option) => {
                if (option && option.label) {
                  setFieldsValue({
                    holduserid: value,
                    holdusername: option.label
                  });
                }
              }
            }
          };
        }

        // 为 isepiboly 添加 onChange 监听
        if (schema.field === 'isepiboly') {
          return {
            ...schema,
            componentProps: {
              ...schema.componentProps,
              onChange: (value) => {
                formState.isepiboly = value;
                formState.selectedEpibolyUnit = null; //  重置单位选择

                // 清空相关选择
                setFieldsValue({
                  epibolyunit: undefined,
                  holdusername: undefined,
                  holduserid: undefined
                });
              }
            }
          };
        }

        // 为 isperson 添加 onChange 监听
        if (schema.field === 'isperson') {
          return {
            ...schema,
            componentProps: {
              ...schema.componentProps,
              onChange: (e) => {
                const value = e.target ? e.target.value : e;
                formState.isperson = value;
                formState.selectedEpibolyUnit = null; // ✅ 重置单位选择

                // 清空相关选择
                setFieldsValue({
                  epibolyunit: undefined,
                  holdusername: undefined,
                  holduserid: undefined
                });
              }
            }
          };
        }

        if (schema.field === 'attachment') {
          return {
            ...schema,
            componentProps: {
              ...schema.componentProps,
              api: uploadApi,
              maxSize: 10,
              multiple: true,
              accept: ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'],
              emptyHidePreview: true,
              showPreviewNumber: true,
              afterUpload: (list) => {
                return list.map(item => ({
                  id: item.id || `file-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`,
                  name: item.name || item.fileName,
                  type: item.type || getFileExtension(item.name || item.fileName),
                  path: item.url || item.path,
                  size: item.size,
                  uploadTime: item.uploadTime || new Date().toISOString()
                }));
              },
            }
          };
        }
        return schema;
      });
    }

    // 表单设置
    const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue, updateSchema }] = useForm({
      labelWidth: 100,
      schemas: createDynamicFormSchema(), // 使用动态schema
      showActionButtonGroup: false,
      baseColProps: { span: 24 },
      helpMessage: '支持JPG、PNG、PDF、DOC格式，单个文件不超过10MB'
    });

    // 预加载所有数据
    async function preloadAllData() {

      try {
        // 并行加载所有数据
        await Promise.all([
          loadEpibolyUnits(),
          loadEpibolyPersons(),
          loadSystemPersonnel()
        ])

      } catch (error) {
        console.error('预加载数据失败:', error);
      }
    }

    //3.新增加载系统人员的函数
    async function loadSystemPersonnel(){
      try {

        const result = await getOrgUsers(orgcode.value);

        if (result && Array.isArray(result)){
          // 将api返回的数据映射为持证人选着需要的格式
          dataCache.systemPersonnel = result.map(user => ({
            userid: user.id,           // UserSimpleInfoDto.id -> userid
            username: user.name        // UserSimpleInfoDto.name -> username
          }));

        }else {
          console.warn('系统人员API返回数据格式异常:', result);
          dataCache.systemPersonnel = [];
        }
      }catch (error) {
        console.error('加载系统人员失败:', error);

        // API调用失败时使用空数组，避免界面报错
        dataCache.systemPersonnel = [];

        // 可选：显示错误提示给用户
        createMessage.warning('加载系统人员失败，请刷新后重试');
      }
    }

    // 加载相关方单位
    async function loadEpibolyUnits() {
      try {
        const result = await queryEpibolyUnit({ orgcode: orgcode.value });

        if (result && Array.isArray(result)) {
          dataCache.epibolyUnits = result;
        }
      } catch (error) {
        console.error('加载相关方单位失败:', error);
      }
    }

    // 加载相关方人员
    async function loadEpibolyPersons() {
      try {

        // 确保已经加载了相关方单位数据
        if (dataCache.epibolyUnits.length === 0) {
          await loadEpibolyUnits();
        }


        // 如果没有相关方单位，直接返回空数组
        if (dataCache.epibolyUnits.length === 0) {
          dataCache.epibolyPersons = [];
          return;
        }

        const result = await queryCertificateInfo({
          orgcode: orgcode.value,
          isepiboly: true,
          holdtype: '2',
          keywords: '',
          status: ''
        });
        dataCache.epibolyPersons = Array.from(result.values());

      } catch (error) {
        console.error('加载相关方人员失败:', error);
        dataCache.epibolyPersons = [];

        // 可选：显示错误提示给用户
        createMessage.warning('加载相关方人员失败，请刷新后重试');
      }
    }

    // 监听计算属性变化并更新字段
    watch(
        [holdUserOptions, placeholderText],
        () => {
          // 延迟执行，确保表单已经初始化
          setTimeout(() => {
            updateHoldUserField();
          }, 100);
        },
        { deep: true, immediate: false }
    );

    // 7. ✅ 修改 updateHoldUserField 函数
    function updateHoldUserField() {
      const options = holdUserOptions.value;
      const { isepiboly, isperson, selectedEpibolyUnit } = formState;

      // 动态标签逻辑
      let holdUserLabel = '持证人/单位';
      if (isperson === true) {
        holdUserLabel = '持证人员';
      } else if (isperson === false) {
        holdUserLabel = '持证单位';
      }

      // 动态占位符逻辑
      let holdUserPlaceholder = '请选择持证人';

      if (isepiboly && isperson) {
        if (!selectedEpibolyUnit) {
          holdUserPlaceholder = '请先选择相关方单位';
        } else {
          holdUserPlaceholder = '请选择该单位下的人员';
        }
      } else if (isepiboly && !isperson) {
        holdUserPlaceholder = '请选择相关方单位';
      } else if (!isepiboly && isperson) {
        holdUserPlaceholder = '请选择系统人员';
      }

      updateSchema([
        // 更新相关方单位选项
        {
          field: 'epibolyunit',
          componentProps: {
            options: epibolyUnitOptions.value,
            placeholder: '请选择相关方单位'
          }
        },
        // 更新持证人选项
        {
          field: 'holdusername',
          label: holdUserLabel,
          componentProps: {
            options: options,
            placeholder: holdUserPlaceholder,
            fieldNames: { label: 'label', value: 'value' },
            allowClear: true,
            onChange: (value, option) => {
              if (option && option.label) {
                setFieldsValue({
                  holduserid: value,
                  holdusername: option.label
                });
              }
            }
          }
        }
      ]);
    }

    async function getCertificateById() {
      try {
        const res = await getCertificateInfo(dataId.value);

        // 解析附件数据
        let attachmentData = [];
        if (res.attachment) {
          try {
            let parsedAttachment = JSON.parse(res.attachment);
            attachmentData = Array.isArray(parsedAttachment) ? parsedAttachment : [parsedAttachment];
            attachmentData = attachmentData.filter(item => item && item.id).map(item => ({
              id: item.id,
              name: item.name || '未命名文件',
              type: item.type || ''
            }));
          } catch (e) {
            console.error('附件数据解析失败:', e);
          }
        }

        // 准备设置的表单值
        const formData = {
          ...res,
          isepiboly: res.isepiboly || res.isepiboly === '1',
          isperson: res.isperson || res.isperson === '1',
          attachment: attachmentData,
        };

        // 同步到响应式状态
        formState.isepiboly = formData.isepiboly;
        formState.isperson = formData.isperson;

        // 设置表单值
        await setFieldsValue(formData);

      } catch (ex) {
        console.error('获取证照数据失败:', ex);
        createMessage.error('获取证照数据失败');
      }
    }

    // 2. 修复后的 useModalInner 函数
    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {

      // 🎯 关键改进：立即设置loading状态，防止显示旧数据
      setModalProps({
        confirmLoading: true,
        okButtonProps: { disabled: true }
      });

      try {
        // 判断是否来自抽屉
        const isFromDrawer = data.fromDrawer === true;

        // 设置基础数据
        if (data?.operateType) op.value = data.operateType;
        if (data?.id) dataId.value = data.id;
        if (data?.orgcode) orgcode.value = data.orgcode;

        // 设置标题
        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value !== OperationTypeEnum.UN_KNOWN && op.value !== OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        // 重置表单 - 在数据加载前先清空
        resetFields();

        // 设置表单初始值 - 先设置已知的值
        const formValues = {
          orgcode: data.orgcode || orgcode.value,
          isepiboly: data.isepiboly !== undefined ? data.isepiboly : false,
          isperson: data.isperson !== undefined ? data.isperson : true,
          holduserid: data.holduserid,
          holdusername: data.holdusername,
        };

        // 同步到响应式状态
        formState.isepiboly = formValues.isepiboly;
        formState.isperson = formValues.isperson;

        // 立即设置表单值
        await setFieldsValue(formValues);

        // ✅ 如果是抽屉模式，优先处理UI状态（移到这里）
        if (isFromDrawer) {

          updateSchema([
            {
              field: 'isepiboly',
              componentProps: { disabled: true },
              show: false
            },
            {
              field: 'isperson',
              componentProps: { disabled: true },
              show: false
            },
            {
              field: 'holdusername',
              show: false,
              componentProps: {
                disabled: true,
                placeholder: `持证人: ${data.holdusername}`,
                options: [],
              },
            },
            {
              field: 'epibolyunit',
              ifShow: false, // ✅ 抽屉模式完全不渲染辅助字段
              componentProps: {
                disabled: true,
                options: [],
              },
            }
          ]);
        }

        // 并行执行：数据预加载 + 编辑数据加载
        const tasks = [preloadAllData()];

        if (op.value === OperationTypeEnum.EDIT && dataId.value) {
          tasks.push(getCertificateById());
        }

        // 等待所有异步任务完成
        await Promise.all(tasks);

        // 非抽屉模式才需要更新holdusername字段
        if (!isFromDrawer) {
          // 延迟更新字段选项，确保数据已加载
          setTimeout(() => {
            updateHoldUserField();
          }, 100);
        }

      } catch (error) {
        console.error('模态框初始化失败:', error);
        createMessage.error('数据加载失败，请重试');
      } finally {
        // 🎯 关键改进：数据准备完毕后才移除loading状态
        setModalProps({
          confirmLoading: false,
          okButtonProps: { disabled: false }
        });
      }
    });

    // 提交表单
    // 3. 修复后的 onButtonOkClick 函数
    async function onButtonOkClick() {
      try {
        const values = await validate();
        setModalProps({ confirmLoading: true });

        let attachmentData = values.attachment;
        if (attachmentData && Array.isArray(attachmentData)) {
          attachmentData = attachmentData.map(item => ({
            id: item.id,
            name: item.name || '未命名文件',
            type: item.type || getFileExtension(item.name || '')
          }));
          attachmentData = JSON.stringify(attachmentData);
        } else {
          attachmentData = JSON.stringify([]);
        }

        const certificateData: CertificateDto = {
          ...values,
          attachment: attachmentData,
          id: op.value === OperationTypeEnum.EDIT ? dataId.value : '',
          orgcode: orgcode.value,
          holduserid: values.holduserid
          // 注意：不包含 epibolyunit 字段，因为它只是UI辅助字段
        };

        if (op.value === OperationTypeEnum.ADD) {
          const result = await addCertificateInfo(certificateData);
          if (!result || Object.keys(result).length == 0) {
            createMessage.success('新增成功');
            opSuccess();
          } else {
            createMessage.error('新增失败');
          }
        } else if (op.value === OperationTypeEnum.EDIT) {
          const result = await updateCertificateInfo(certificateData);
          if (!result || Object.keys(result).length == 0) {
            createMessage.success('修改成功');
            opSuccess();
          } else {
            createMessage.error('修改失败');
          }
        }
      } catch (error) {
        console.error('提交数据失败:', error);
        createMessage.error('提交失败，请检查表单');
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    // 操作成功后的回调
    function opSuccess() {
      closeModal();
      emit('success');
    }

    return {
      registerModal,
      registerForm,
      modalTitle,
      onButtonOkClick,
      formState,
      holdUserOptions
    };
  },
});
</script>

<style scoped lang="less">
.upload-container {
  margin-bottom: 16px;
}
</style>
